package com.alcj.controller;

import com.alcj.common.base.BaseController;
import com.alcj.common.constant.SysConstant;
import com.alcj.common.utils.CmnUtil;
import com.alcj.common.utils.MultipartFileUtil;
import com.alcj.common.utils.StringUtils;
import com.alcj.model.CarData;
import com.alcj.model.User;
import com.alcj.service.CarDataService;
import com.alcj.service.UserService;
import com.alibaba.fastjson.JSON;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author :wdl
 * @version :v1.0
 * @Package :com.alcj.controller
 * @Description :${TODO}(车辆资料)
 * @date :2017/10/20 0005 上午 11:10
 */
@Controller
@RequestMapping("/carData")
public class CarDataController  extends BaseController {

    @Autowired
    UserService userService;
    @Autowired
    private CarDataService carDataService;

    //private String user_id="0";


    /**
     * @Author:wdl
     * @Description:车辆资料list和模糊查询方法
     * @param carData
     * @param request
     * @param response
     * @param model
     * @return String
     */
    @RequestMapping("/list")
    public String list(CarData carData, HttpServletRequest request, HttpServletResponse response, Model model) {
        try{
             User sysUser = (User) request.getSession().getAttribute("User");
            if (CmnUtil.isEmpty(sysUser)){

                return SysConstant.INDEX_PAGE;

            }

            if (StringUtils.isEmpty(carData.getId())){
                carData.setUser(sysUser);
            }
            //该用户的所有车辆
            List<CarData> listCarData = carDataService.findList(carData);
            String objStr=  JSON.toJSONString(listCarData);
            model.addAttribute("carDataUser", sysUser);
            model.addAttribute("listCarData", listCarData);
            model.addAttribute("carDatajson", objStr);
        } catch (Exception e) {
            // 异常报错
            logger.error("用户注册异常 : {}", e.getMessage());
            logger.error("异常详细信息 :", e);
            return SysConstant.ERROR_PAGE_500;
        }

        return "carData";
    }

    /**
     * @Author:wdl
     * @Description:保存车辆资料和人车关系
     * @param request
     * @return Map
     * */
    @RequestMapping("/saveCarData")
    public String  doSave(@RequestParam("imgUrl") MultipartFile imgUrl,HttpServletRequest request, Model model) {
        CarData carData=new CarData();
        try{
            String id = (String) request.getParameter("id");
            String recognitionCode = (String) request.getParameter("recognitionCode");
            String plateNumber = (String) request.getParameter("plateNumber");
            String plateType = (String) request.getParameter("plateType");
            String holder = (String) request.getParameter("holder");
            String registerDate = (String) request.getParameter("registerDate");
            String brandModel = (String) request.getParameter("brandModel");
            String address = (String) request.getParameter("address");
            String fuelType = (String) request.getParameter("fuelType");
            String projectNature = (String) request.getParameter("projectNature");
            carData.setId(id);
            carData.setRecognitionCode(recognitionCode);
            carData.setPlateNumber(plateNumber);
            carData.setPlateType(plateType);
            carData.setHolder(holder);
            carData.setBrandModel(brandModel);
            carData.setAddress(address);
            carData.setFuelType(fuelType);
            carData.setProjectNature(projectNature);
            if(StringUtils.isNotBlank(registerDate)){
                SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");//小写的mm表示的是分钟
                carData.setRegisterDate(sdf.parse(registerDate));
            }
            //整合之后需要放开的代码
            User sysUser = (User) request.getSession().getAttribute("User");
            if (CmnUtil.isEmpty(sysUser)){

                return SysConstant.INDEX_PAGE;

            }
            carData.setUser(sysUser);
            if(imgUrl.isEmpty()){
                carData.setImgUrl(null);
            }else{
                String  uploadName = MultipartFileUtil.uploadFilePath(imgUrl,"web.driving-path");
                carData.setImgUrl(uploadName);
            }

            carDataService.insert(carData);
            model.addAttribute("success",true);
            model.addAttribute("message","保存车辆资料成功");
           // map.put("success",true);
           // map.put("message","保存车辆资料成功");
        } catch (Exception e) {
            // 异常报错
            logger.error("用户注册异常 : {}", e.getMessage());
            logger.error("异常详细信息 :", e);
            return SysConstant.ERROR_PAGE_500;
        }
        return "redirect:/carData/list";
    }


    /**
     * @Author:wdl
     * @Description:更多获取车牌list
     * @param carData
     * @param request
     * @return Map
     * */
    @RequestMapping("/searchCarData")
    @ResponseBody
    public Map searchCarData(CarData carData, HttpServletRequest request) {
        Map map=new HashMap<>();

        try{
            //整合之后需要放开的代码
            User sysUser = (User) request.getSession().getAttribute("User");
            if (StringUtils.isEmpty(carData.getId())){
                carData.setUser(sysUser);
            }
            //该用户的所有车辆
            List<CarData> listCarData = carDataService.findList(carData);
            if(listCarData.size()>0){
                map.put("success",true);
                map.put("dataList",listCarData);
            }else{
                map.put("success",false);
                map.put("message","查询无数据");
            }
        } catch (Exception e) {
            // 异常报错
            logger.error("用户注册异常 : {}", e.getMessage());
            logger.error("异常详细信息 :", e);
        }
        return map;
    }

    /**
     * @Author:wdl
     * @Description:车辆自动识别
     * @param carData
     * @param request
     * @return Map
     * */
    @RequestMapping("/autoRecognition")
    @ResponseBody
    public Map autoRecognition( CarData carData, HttpServletRequest request) {
        Map map=new HashMap<>();
        if(carData==null){
            map.put("success",false);
            map.put("message","识别失败");
            return map;
        }
        //TODO 调用接口


        map.put("success",true);
        map.put("message","功能开发中");
        return map;
    }

    /**
     * @Author:wdl
     * @Description:解除绑定
     * @param carData
     * @param model
     * @return String
     * */
    @RequestMapping("/deleteCarUser")
    public String delete(CarData carData,Model model, HttpServletRequest request) {
        try{
            if (carData.getUser()==null || StringUtils.isEmpty(carData.getUser().getUserid())){
                User sysUser = (User) request.getSession().getAttribute("User");
                if (CmnUtil.isEmpty(sysUser)){
                    return SysConstant.INDEX_PAGE;
                }
                carData.setUser(sysUser);
            }
            carDataService.deleteCarUser(carData);
        } catch (Exception e) {
            // 异常报错
            logger.error("用户注册异常 : {}", e.getMessage());
            logger.error("异常详细信息 :", e);
            return SysConstant.ERROR_PAGE_500;
        }
        model.addAttribute("messsage", "解除绑定成功");
        return "redirect:/carData/list";
    }

    /**
     * @Author:wdl
     * @Description:认证车主
     * @param identitycard
     * @param model
     * @return String
     * */
    @RequestMapping("/ownerCar")
    public String ownerCar(@RequestParam("identitycard") MultipartFile identitycard,HttpServletRequest request, Model model) {
        try{  //TODO 提交审核
            CarData carData=new CarData();
            User sysUser = (User) request.getSession().getAttribute("User");
            if (CmnUtil.isEmpty(sysUser)){
                return SysConstant.INDEX_PAGE;
            }
            String id = (String) request.getParameter("idUpload");

            if(!identitycard.isEmpty()){
                String  uploadName = MultipartFileUtil.uploadFilePath(identitycard,"web.identitycard-path");
               // carData.setImgUrl(uploadName);
            }
            carData.setId(id);
            carData.setIsOwner("1");
            carData.setUser(sysUser);
            carDataService.insert(carData);
           model.addAttribute("messsage", "功能开发中");
        } catch (Exception e) {
            // 异常报错
            logger.error("用户注册异常 : {}", e.getMessage());
            logger.error("异常详细信息 :", e);
            return SysConstant.ERROR_PAGE_500;
        }
        return "redirect:/carData/list";
    }


    /**
     * @Author:wdl
     * @Description:管理车主关系
     * @param model
     * @return String
     * */
    @RequestMapping("/manageHoderCar")
    public String manageHoderCar(CarData carData,HttpServletRequest request, Model model) {
        try{
            //carDataService.insert(carData);
            //TODO
            model.addAttribute("messsage", "解除认证车主");
        } catch (Exception e) {
            // 异常报错
            logger.error("用户注册异常 : {}", e.getMessage());
            logger.error("异常详细信息 :", e);
            return SysConstant.ERROR_PAGE_500;
        }
        return "redirect:/carData/list";
    }

    /**
     * @Author:wdl
     * @Description:更新汽车更新时间
     * @param model
     * @return String
     * */
    @RequestMapping("/updateTime")
    @ResponseBody
    public Map updateTime(CarData carData,HttpServletRequest request, Model model) {
        Map map=new HashMap<>();
        try{
            if(carData!=null&&StringUtils.isNotBlank(carData.getId())){
                carDataService.insert(carData);
                map.put("success",true);
                map.put("message","修改成功");
                return map;
            }
            map.put("success",false);
            map.put("message","修改失败");
        } catch (Exception e) {
            // 异常报错
            logger.error("用户注册异常 : {}", e.getMessage());
            logger.error("异常详细信息 :", e);
           // return SysConstant.ERROR_PAGE_500;
        }
        return map;
    }



    /**
     * @Author:wdl
     * @Description:验证车辆代码的唯一性
     * @param model
     * @param carData
     * @return map
     * */
    @RequestMapping("/validatingCode")
    @ResponseBody
    public Map validatingCode(CarData carData,HttpServletRequest request, Model model) {
        Map map=new HashMap<>();
        try{
            if(carData!=null&&StringUtils.isNotBlank(carData.getRecognitionCode())){
                CarData reCarData=carDataService.validatingCode(carData);
                if (reCarData==null){
                    map.put("success",true);
                }else {
                    map.put("success",false);
                    map.put("message","该车辆代码已存在!请重新填写.");

                }
                return map;
            }
            map.put("success",false);
            map.put("message","");
        } catch (Exception e) {
            // 异常报错
            logger.error("用户注册异常 : {}", e.getMessage());
            logger.error("异常详细信息 :", e);
            // return SysConstant.ERROR_PAGE_500;
        }
        return map;
    }
    /**
     * @Author:wdl
     * @Description:管理车主获取list
     * @param model
     * @param carData
     * @return map
     * */
    @RequestMapping("/findListById")
    @ResponseBody
    public Map findListById(CarData carData,HttpServletRequest request, Model model) {
        Map map=new HashMap<>();
        try{
            List<CarData> list=new ArrayList<CarData>();
            User sysUser = (User) request.getSession().getAttribute("User");
            carData.setUser(sysUser);
            if(carData!=null&&StringUtils.isNotBlank(carData.getId())){
                list=carDataService.findListById(carData);
                if (list.size()>0){
                    map.put("success",true);
                    map.put("dataList",list);
                }else {
                    map.put("success",false);
                    map.put("message","该车辆不存在其他绑定情况。");

                }
                return map;
            }
            map.put("success",false);
            map.put("message","");
        } catch (Exception e) {
            // 异常报错
            logger.error("用户注册异常 : {}", e.getMessage());
            logger.error("异常详细信息 :", e);
            // return SysConstant.ERROR_PAGE_500;
        }
        return map;
    }
}
